<template>
  <div class="toTop" ref="toTopButton" @click="ScrolltoTop">
        <i  class="iconfont icon-ai-top"></i>
  </div>
</template>

<script>
import { throttleScroll } from "@/utils/util";
export default {
    mounted(){
        if (this.$refs.toTopButton) {
      // 使用节流滚动事件
      const handleScroll = throttleScroll(this.handleScroll, 1000);
      window.addEventListener("scroll", handleScroll);
    }
    },
    beforeDestroy() {
    // 清理事件监听器
    window.removeEventListener("scroll", this.handleScroll);
  },
    methods:{
 //显示返回顶部按钮
 appear() {
      const element = this.$refs.toTopButton;
      if (element) {
        element.style.opacity = 1; // 改变文字颜色透明度
      }
    },
    //隐藏返回顶部按钮
    hide() {
      const element = this.$refs.toTopButton;
      if (element) {
        element.style.opacity = 0; // 改变文字颜色透明度
      }
    },
    handleScroll() {
      // 用户滚动到一定位置后，显示返回顶部按钮
      if (window.scrollY > 400) this.appear(); 
      else this.hide();
    },
    ScrolltoTop() {
      window.scrollTo({
        top: 0,
        behavior: "smooth", // 使用平滑滚动
      });
    },
    }
}
</script>

<style scoped>
.toTop{
    position: fixed;
    width:45px;
    height:45px;
    background:  rgb(72,110,99,0.8);
    transition: .2s; /* 设置变换效果 */
    opacity: 0; /* 默认情况下，按钮透明 */
    position: fixed;
    bottom: 50px;
    right: 60px;
    text-align: center;
    line-height: 50px;
    border-radius:5px ;
    color: #B2C3BB;
}
.icon-ai-top {
  font-size: 22px;
  cursor: pointer;
}
.toTop:hover{
  color: #fff;
  background:  #2A514D;
}
</style>